import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/constants/index.dart';
import 'package:flutter_house_manager/controller/BuildController.dart';
import 'package:flutter_house_manager/utils/PromptAction.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String _currentAddress = '';
  List _aroundList = [];
  BuildController buildController = Get.put(BuildController());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAccess(); //  申请获取地理定位的权限
  }

  void getAccess() async {
    PermissionStatus status = await Permission.location.request(); // 申请定位权限
    if (status == PermissionStatus.granted) {
      PromptAction.showSuccess("用户同意授权");
      getLocation();
      // 可以获取定位了
    } else {
      PromptAction.showSuccess("用户拒绝授权");
    }
  }

  void getLocation() async {
    try {
      Position p = await Geolocator.getCurrentPosition();
      // PromptAction.showToast('${p.latitude},${p.longitude}');
      getLocationString(p.latitude, p.longitude); //获取当前地址
      getNearList(p.latitude, p.longitude); //获取附近小区地址
    } catch (e) {
      PromptAction.showToast('获取定位失败' + e.toString());
    }
  }

  // 获取经纬度对应的当前地址
  // lon经度
  // lat纬度
  void getLocationString(double latitude, double longitude) async {
    Dio dio = Dio();
    final res = await dio.get(
        '${GlobalVariable.GAO_BASE_URL}${HTTP_PATH.REGEO}',
        queryParameters: {
          "key": "a4ba68c21377f0c2e39e2a0e86e6cefb",
          "location": "${longitude},${latitude}"
        });
    if (res.data["status"] == "1") {
      _currentAddress = res.data["regeocode"]["formatted_address"];
      setState(() {});
    } else {
      PromptAction.showError("获取定位失败 + 1");
    }
  }

  //获取附近地址
  void getNearList(double latitude, double longitude) async {
    Dio dio = Dio();
    final res = await dio.get(
        '${GlobalVariable.GAO_BASE_URL}${HTTP_PATH.NEARLIST}',
        queryParameters: {
          "key": "a4ba68c21377f0c2e39e2a0e86e6cefb",
          "location": "${longitude},${latitude}",
          "keywords": "公寓",
          "radius": 2000, //米
          "offset": 10 // 限制查询的条数
        });

    if (res.data["status"] == "1") {
      _aroundList = res.data["pois"];
      setState(() {});
    } else {
      PromptAction.showError("获取定位失败");
    }
  }

  List<Widget> getAroundListWidget() {
    // 得到了一个列表
    return _aroundList.map((item) {
      return Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10),
        child: GestureDetector(
          onTap: () {
            // 点击了item
            // 1. 跳转到楼栋列表
            // 2. 传递参数
            // 把点击的小区名称写入到GetX
            buildController.buildInfo["point"] = item["name"];
            buildController.updateBuildInfo(buildController.buildInfo);
            Navigator.pushNamed(context, '/buildinglist');
          },
          child: Row(
            children: [
              Expanded(child: Text(item["name"])),
              const Row(
                children: [
                  Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
                ],
              )
            ],
          ),
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_currentAddress)),
                GestureDetector(
                  onTap: () {
                    getLocationString(39.166613, 117.152827);
                    getNearList(39.166613, 117.152827);
                  },
                  child: const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getAroundListWidget(),
          )
        ],
      ),
    );
  }
}
